package com.tepth.appmanageservice.tools.ext;

import com.tepth.appmanageservice.controllers.Client;

import java.math.BigInteger;
import java.util.ArrayList;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class ExtPro {
	private static Client CLIENT;

	public static void setClient(Client client) {
		CLIENT = client;
	}

	public static Client getClient() {
		return CLIENT;
	}

	public static byte[] AesRandomKeys() {
		return new byte[] { (byte) (Math.random() * (256)), (byte) (Math.random() * (256)), (byte) (Math.random() * (256)), (byte) (Math.random() * (256)), (byte) (Math.random() * (256)),
				(byte) (Math.random() * (256)), (byte) (Math.random() * (256)), (byte) (Math.random() * (256)), (byte) (Math.random() * (256)), (byte) (Math.random() * (256)),
				(byte) (Math.random() * (256)), (byte) (Math.random() * (256)), (byte) (Math.random() * (256)), (byte) (Math.random() * (256)), (byte) (Math.random() * (256)),
				(byte) (Math.random() * (256)) };
	}

	public static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
		byte[] encrypted = cipher.doFinal(clear);
		return encrypted;
	}

	public static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
		SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
		Cipher cipher = Cipher.getInstance("AES");
		cipher.init(Cipher.DECRYPT_MODE, skeySpec);
		byte[] decrypted = cipher.doFinal(encrypted);
		return decrypted;
	}

	public static byte[] encrypt(byte[] aBytes, BigInteger e, BigInteger n) {
		byte[] ab = aBytes;
		if (ab[0] >= 0x80) {
			ab = new byte[ab.length + 1];

			for (int i = 0; i < aBytes.length; i++) {
				ab[i + 1] = aBytes[i];
			}
		}
		BigInteger a = new BigInteger(ab);
		BigInteger data = a.modPow(e, n);
		byte[] dataArray = data.toByteArray();
		if (dataArray[0] == 0) {
			byte[] dataArray2 = new byte[dataArray.length];
			for (int i = 1; i < dataArray.length; i++) {
				dataArray2[i - 1] = dataArray[i];
			}
			return dataArray2;
		}
		return dataArray;
	}

	public static byte[] encryption(byte[] data) {
		ArrayList<Byte> newData = new ArrayList<Byte>();
		newData.add(data[0]);
		for (int i = 1; i < data.length - 1; i++) {
			if (data[i] == 0x7E) {
				newData.add((byte) 0x7D);
				newData.add((byte) 0x02);
				continue;
			} else if (data[i] == 0x7D) {
				newData.add((byte) 0x7D);
				newData.add((byte) 0x01);
				continue;
			}
			newData.add(data[i]);
		}
		newData.add(data[data.length - 1]);

		return ExtToBytes.fromByteArrayList(newData);
	}
}